package com.oa.tools.hr;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.oa.tools.utils.FileUtil;
import com.oa.tools.utils.ObjectUtil;
import com.oa.tools.utils.SecurityUtil;
import com.oa.tools.utils.StringUtil;
import com.oa.tools.utils.SysConfig;
import com.oa.tools.utils.http.OKHttpClientUtil;

public class XRXSReqClient {
	
	//https://api.xinrenxinshi.com/docs.html
	//https://s.xinrenxinshi.com

	public static String xrxs_account = "17182272364";
	public static String xrxs_passwd = "jiekou6666";
	
	public static String xrxsDomain = SysConfig.getSysString("XRXS_DOMAIN");//"https://api.xinrenxinshi.com";
	public static String appKey="appjhLLbyFN378657";//SysConfig.getSysString("XRXS_APP_KEY");//"appadmsTWWB975648";
	public static String appSecret = "fDA*iqd*$%2S2oP2sH2_";//SysConfig.getSysString("XRXS_APP_SECRET");//"dtH@1NusTcx5OkC4YBqH";
	
	public static String userDetailUrl = "/v3/employee/details";				//"/v2/employee/getEmployeeInfoById";
	public static String userUpdateUrl = "/v3/employee/update";					//"/v2/employee/updateEmployee";
	public static String allFieldsUrl = "/v2/employee/getFieldIds";
	public static String allDeptsUrl = "/v3/department/list";					//"/v2/company/getDepartmentList";
	public static String offLineMessgesUrl = "/v2/pushMessage/getFailMessage";
	public static String deptUsersDetailUrl = "/v3/employee/employeeList";// "/v3/employee/employeeSimpleList"; //"/v3/employee/employeeList";//"/v2/employee/getEmployeeListByDepartmentId";
	public static String deptUserSimpleUrl = "/v3/employee/employeeSimpleList";
	
	/**
	 * 通过ID获取用户详情
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public static XRXSPerson getUserDetail(String userId) throws Exception {
		Map<String,Object> params = new HashMap<>();
		params.put("employeeId", userId);
		Map<String,Object> userData = (Map<String, Object>) get(userDetailUrl, params).get("data");
		System.out.println(userId+"-------"+userData);
		
		XRXSPerson xrxsPerson = new XRXSPerson();
			
		xrxsPerson.userId=userId;
		xrxsPerson.mobile = String.valueOf(userData.get("mobile"));
		xrxsPerson.hireType = String.valueOf(userData.get("hireType"));
		xrxsPerson.setName(String.valueOf(userData.get("name")));
		xrxsPerson.entryDate = String.valueOf(userData.get("entryDate"));
		Map<String,Object> fixedFieldMap = (Map<String, Object>) ((Map<String, Object>) userData).get("fields");

		xrxsPerson.fdNo =  String.valueOf(fixedFieldMap.get("工号"));
		xrxsPerson.email =  String.valueOf(fixedFieldMap.get("工作邮箱"));
		xrxsPerson.gender = String.valueOf(fixedFieldMap.get("性别"));
		xrxsPerson.title = String.valueOf(fixedFieldMap.get("岗位"));
		xrxsPerson.rank = String.valueOf(fixedFieldMap.get("职级"));
		xrxsPerson.tel = String.valueOf(fixedFieldMap.get("办公电话"));
		xrxsPerson.departmentId =String.valueOf(fixedFieldMap.get("部门"));
		
		return xrxsPerson;
	}
	
	public static Map<String,XRXSPerson> getDeptDetailUsers(String deptId) throws Exception {
		
		int start = 0;
		int size = 100;
		
		Map<String,XRXSPerson> xrxsPersons = new HashMap<>();
		boolean hasMore = false;
		Map<String,Object> params = new HashMap<>();
		params.put("departmentId", deptId);
		do {
			params.put("offset", start);
			params.put("size",size);
			params.put("fetchChild", "0");
			
			Map<String,Object> userDatas= get(deptUsersDetailUrl, params);
			hasMore= (boolean) userDatas.get("hasMore");
			List<Map<String,Object>> userList= (List<Map<String, Object>>) userDatas.get("userlist");
			for(Map<String,Object> userData:userList) {
				XRXSPerson xrxsPerson = new XRXSPerson();
				xrxsPerson.userId=String.valueOf(userData.get("employeeId"));
				xrxsPerson.mobile = String.valueOf(userData.get("mobile"));
				xrxsPerson.hireType = String.valueOf(userData.get("hireType"));
				xrxsPerson.setName(String.valueOf(userData.get("name")));
				xrxsPerson.entryDate = String.valueOf(userData.get("entryDate"));
				Map<String,Object> fixedFieldMap = (Map<String, Object>) ((Map<String, Object>) userData).get("fields");
	
				xrxsPerson.fdNo =  String.valueOf(fixedFieldMap.get("工号"));
				xrxsPerson.email =  String.valueOf(fixedFieldMap.get("工作邮箱"));
				xrxsPerson.gender = String.valueOf(fixedFieldMap.get("性别"));
				xrxsPerson.title = String.valueOf(fixedFieldMap.get("岗位"));
				xrxsPerson.rank = String.valueOf(fixedFieldMap.get("职级"));
				xrxsPerson.tel = String.valueOf(fixedFieldMap.get("办公电话"));
				xrxsPerson.departmentId =String.valueOf(fixedFieldMap.get("部门"));
				xrxsPersons.put(xrxsPerson.userId, xrxsPerson);
			}
			
			start ++;
		}while(hasMore);
		
		return xrxsPersons;
	}
	
	
	public static Map<String,XRXSPerson> getDeptDetailSimpleUsers(String deptId) throws Exception {
		int start = 0;
		int size = 99;
		
		Map<String,XRXSPerson> xrxsPersons = new HashMap<>();
		boolean hasMore = false;
		Map<String,Object> params = new HashMap<>();
		
		if(!StringUtil.isBlank(deptId)) {
			params.put("departmentId", deptId);
		}
		
		do {
			params.put("offset", start);
			params.put("size",size);
			params.put("fetchChild", 1);
			
			Map<String,Object> userDatas= get(deptUserSimpleUrl, params);
			hasMore= (boolean) userDatas.get("hasMore");
			List<Map<String,Object>> userList= (List<Map<String, Object>>) userDatas.get("userlist");
			for(Map<String,Object> userData:userList) {
				XRXSPerson xrxsPerson = new XRXSPerson();
				xrxsPerson.userId=String.valueOf(userData.get("employeeId"));
				xrxsPerson.mobile = String.valueOf(userData.get("mobile"));
				xrxsPerson.hireType = String.valueOf(userData.get("hireType"));
				xrxsPerson.setName(String.valueOf(userData.get("name")));
				xrxsPerson.entryDate = String.valueOf(userData.get("entryDate"));
				xrxsPersons.put(xrxsPerson.userId, xrxsPerson);
			}
			
			start ++;
		}while(hasMore);
		
		return xrxsPersons;
	}
	
	public static Map<String,Object> getAllMessages() throws Exception {
		
		Map<String,Object> rtnMsg = get(offLineMessgesUrl, null);
		
		return rtnMsg;
	}
	
	
	
	/**
	 * 更新用户信息
	 * @param userId		用户id
	 * @param name			用户姓名
	 * @param mobile		手机
	 * @param entryDate		入职日期
	 * @param hireType		招聘类型
	 * @param fieldName		要更新的字段名称
	 * @param fieldValue	要更新的字段值
	 * @return
	 * @throws Exception
	 */
	public static Map<String,Object> updateUserInfo(String userId,String name,String mobile,String entryDate,String hireType,String fieldName,String fieldValue)throws Exception {
		
		Map<String,String> params = new HashMap<>();
		params.put("employeeId", userId);
		params.put("name", name);
		params.put("mobile",mobile);
		params.put("entryDate",entryDate);
		params.put("hireType", hireType);
		
		Map<String,Object> updateField = new HashMap<>();
		updateField.put(fieldName, fieldValue);
		params.put("fields", StringUtil.object2String(updateField));

		return post(userUpdateUrl, params);
	}
	
	public static Map<String,Object> getALLFields() throws Exception {
		return get(allFieldsUrl, null);
	}
	
	public static Map<String,XRXSDept> getAllDepts(String departmentId,boolean fetchChild) throws Exception {
		
		Map<String,Object> params = new HashMap<>();
		params.put("departmentId", departmentId);
		if(fetchChild) {
			params.put("fetchChild", 1);
		}else {
			params.put("fetchChild", 0);
		}
		
		Map<String,Object> rtnMap =  get(allDeptsUrl, params);
		Map<String,XRXSDept> depts = new HashMap<>();
		
		List<Map<String,Object>> deptMapList = (List<Map<String, Object>>) rtnMap.get("department");
		
		for(Map<String,Object> deptMap:deptMapList) {
			XRXSDept xrxsDept = ObjectUtil.map2Object(deptMap, XRXSDept.class);
			depts.put(String.valueOf(deptMap.get("departmentId")),xrxsDept);
//			System.out.println(deptMap);
		}
		
		return depts;
	}

	public static void main(String[] args) throws Exception {

//		System.out.println(getAllMessages());
		
		System.out.println(getUserDetail("f0b4530e0e3f4e9689c7bd6a5ff8e9c8"));
	}
	
	public static void test() throws Exception {
//		Map<String, XRXSPerson> personMap = getDeptDetailSimpleUsers(null);
		
//		getUserDetail("8634ca87f8ef45d29b206b27e9091089");
		
		
		Map<String,XRXSDept>  deptMap= XRXSReqClient.getAllDepts("",true);
		
		String file1 = "C:\\Users\\dell\\Desktop\\20181011\\user1.txt";
		String file = "C:\\Users\\dell\\Desktop\\20181011\\user.txt";
		
		new File(file1).delete();
		new File(file).delete();
		
		for(XRXSDept dept:deptMap.values()) {
//			System.out.println(dept.getDepartmentId());
			String deptId = dept.getDepartmentId();
			String deptName = dept.getName();
			String adminId = dept.getAdminId();
			String deptCode = dept.getCode();
			
			StringBuilder updateSql = new StringBuilder();
			
//			updateSql.append("update sys_org_element set fd_import_info = 'OA-TOOL");
//			updateSql.append(deptId.trim());
//			updateSql.append("' where fd_name = '");
//			updateSql.append(deptName.trim());
//			updateSql.append("' and fd_is_available = 1;");
			
			FileUtil.writeTxt2File(updateSql.toString(),file1);
			
		
			Map<String, XRXSPerson> personMap = getDeptDetailUsers(deptId);
		
			for(XRXSPerson per:personMap.values()) {
				String perId = per.getUserId();
				String perName = per.getName();
				String fdNo = per.getFdNo();
//				FileUtil.writeTxt2File("|"+perId+"|"+perName+"|"+fdNo+"|",file);
				
				StringBuilder updatePerSql = new StringBuilder();
				
//				updatePerSql.append("update sys_org_element set fd_import_info = 'OA-TOOL");
//				updatePerSql.append(perId.trim());
//				updatePerSql.append("' where fd_name = '");
//				updatePerSql.append(perName.trim());
//				updatePerSql.append("' and fd_no='");
//				updatePerSql.append(StringUtil.parseString(fdNo));
//				updatePerSql.append("' and fd_is_available = 1;");
				
				updatePerSql.append(perName);updatePerSql.append("-");
				updatePerSql.append(perId);updatePerSql.append("-");
				updatePerSql.append(per.getRank());
				
				FileUtil.writeTxt2File(updatePerSql.toString(),file);
				
			}
			
			System.out.println("------------------------------------------------------");
			
		}
//		System.out.println("------------------------------------------------------");
//		Map<String, XRXSPerson> personMap = getDeptDetailSimpleUsers(null);
//		
//		for(XRXSPerson per:personMap.values()) {
//			String perId = per.getUserId();
//			String perName = per.getName();
//			String fdNo = per.getFdNo();
////			FileUtil.writeTxt2File("|"+perId+"|"+perName+"|"+fdNo+"|",file);
//			
//			StringBuilder updatePerSql = new StringBuilder();
//			
//			updatePerSql.append("update sys_org_element set fd_import_info = 'OA-TOOL");
//			updatePerSql.append(perId.trim());
//			updatePerSql.append("' where fd_name = '");
//			updatePerSql.append(perName.trim());
//			updatePerSql.append("' and fd_no='");
//			updatePerSql.append(StringUtil.parseString(fdNo));
//			updatePerSql.append("' and fd_is_available = 1;");
//			
//			FileUtil.writeTxt2File(updatePerSql.toString(),file);
//			
//		}
		
		
//		Map<String, XRXSPerson> personMap = getDeptDetailUsers("c22627ce18f34ac0ba6dbb760f74d00f");
//		Map<String,XRXSDept> xrxsDeptMap = XRXSReqClient.getAllDepts("",false);
//		
//		System.out.println(xrxsDeptMap.size());
//		
//xrxsDeptMap = XRXSReqClient.getAllDepts("",true);
//		
//		System.out.println(xrxsDeptMap.size());
		
//		Map<String, XRXSPerson> personMap = getDeptDetailUsers("55e65d5ea226422db74e10b77a3db11b");
//		for(XRXSPerson per:personMap.values()) {
//			System.out.println(per);
//			
//		}
	}
	
	private static Map<String,Object> get(String apiUrl,Map<String,Object> params) throws Exception{
		StringBuilder url = new StringBuilder();
		url.append(xrxsDomain);
		url.append(apiUrl);
		url.append("?");
		if(params==null) {
			params = new HashMap<String,Object>();
		}
		params.put("appKey", appKey);
		params.put("timestamp", String.valueOf(System.currentTimeMillis()));
		List<String> list=new ArrayList<String>(params.keySet());
		Collections.sort(list);
		StringBuilder signSrc = new StringBuilder();
		for(String key:list) {
			signSrc.append(key);signSrc.append("=");signSrc.append(params.get(key));signSrc.append("&");
		}
		url.append(signSrc);
		String sign = SecurityUtil.encryptHmacSHA1(signSrc.substring(0, signSrc.length()-1), appSecret);
		sign = URLEncoder.encode(sign,"utf-8");
		url.append("sign=");url.append(sign);
		
		System.out.println(url);
		String [] result = OKHttpClientUtil.httpGet(url.toString(), null, null);
		FileUtil.writeTxt2File(result[0],"C:\\Users\\dell\\Desktop\\20181011\\1.txt");
		System.out.println(result[0]);
		
		Map<String,Object> retDataMap = ObjectUtil.json2Map(result[0]);
		
/*//		Map<String,Object> dataMap = null;
		if("0".equals(String.valueOf(retDataMap.get("code")))) {
//			String dataSec = (String) retDataMap.get("data");
//			String data = AESUtil.decrypt(dataSec, appSecret);
//			dataMap = ObjectUtil.json2Map(data);	
		}*/
		
		return retDataMap;
	}
	
	private static Map<String,Object> post(String apiUrl,Map<String,String> params) throws Exception{
		
		StringBuilder url = new StringBuilder();
		url.append(xrxsDomain);
		url.append(apiUrl);
		url.append("?");
		
		if(params==null) {
			params = new HashMap<String,String>();
		}
		
		params.put("appKey", appKey);
		long timeMill = System.currentTimeMillis();
		params.put("timestamp", String.valueOf(timeMill));
		List<String> list=new ArrayList<String>(params.keySet());
		Collections.sort(list);
		StringBuilder signSrc = new StringBuilder();
		for(String key:list) {
			signSrc.append(key);signSrc.append("=");signSrc.append(params.get(key));signSrc.append("&");
		}
		url.append("appKey=");url.append(appKey);url.append("&");
		url.append("timestamp=");url.append(timeMill);url.append("&");
		String sign = SecurityUtil.encryptHmacSHA1(signSrc.substring(0, signSrc.length()-1), appSecret);
		sign = URLEncoder.encode(sign,"utf-8");
		url.append(signSrc);
		url.append("sign=");url.append(sign);
		
		String [] result = OKHttpClientUtil.httpPost(url.toString(), null, null);
		System.out.println(url+"---post----"+result[0]);
		
		Map<String,Object> retDataMap = ObjectUtil.json2Map(result[0]);
		
	/*	Map<String,Object> dataMap = null;
		if("0".equals(String.valueOf(retDataMap.get("code")))) {
			String dataSec = (String) retDataMap.get("data");
//			String data = AESUtil.decrypt(dataSec, appSecret);
//			dataMap = ObjectUtil.json2Map(data);	
		}*/
		
		return retDataMap;
	}
	
	public static class XRXSPerson{
		
		/**
		 * XRXS 的员工ID
		 */
		private String userId;
		/**
		 * 手机号
		 */
		private String mobile;
		/**
		 * 聘用类型
		 */
		private String hireType;
		private String name;
		/**
		 * 入职日期
		 */
		private String entryDate;
		/**
		 * 工号
		 */
		private String fdNo;  
		/**
		 * 性别 ：男|女
		 */
		private String gender;
		/**
		 * 岗位
		 */
		private String title; 
		
		/**
		 * 职级
		 */
		private String rank;
		
		/**
		 * 工作电话
		 */
		private String tel;
		
		/**
		 * 工作邮箱
		 */
		private String email;
		
		/**
		 * 部门XRXSID
		 */
		private String departmentId;
		public String getMobile() {
			return mobile;
		}
		public void setMobile(String mobile) {
			this.mobile = mobile;
		}
		public String getHireType() {
			return hireType;
		}
		public void setHireType(String hireType) {
			this.hireType = hireType;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			name = name.replaceAll("[x00-xff]", "").replace("\u00a0", "");
//			name = name.replaceAll("[^\u4e00-\u9fa5\\-a-zA-Z0-9]", "");
			this.name = name;
		}
		public String getEntryDate() {
			return entryDate;
		}
		public void setEntryDate(String entryDate) {
			this.entryDate = entryDate;
		}
		public String getFdNo() {
			return fdNo;
		}
		public void setFdNo(String fdNo) {
			this.fdNo = fdNo;
		}
		public String getGender() {
			return gender;
		}
		public void setGender(String gender) {
			this.gender = gender;
		}
		public String getTitle() {
			return title;
		}
		public void setTitle(String title) {
			this.title = title;
		}
		public String getRank() {
			return rank;
		}
		public void setRank(String rank) {
			this.rank = rank;
		}
		public String getTel() {
			return tel;
		}
		public void setTel(String tel) {
			this.tel = tel;
		}
		public String getDepartmentId() {
			return departmentId;
		}
		public void setDepartmentId(String departmentId) {
			this.departmentId = departmentId;
		}
		public String getUserId() {
			return userId;
		}
		public void setUserId(String userId) {
			this.userId = userId;
		}
		public String getEmail() {
			return email;
		}
		public void setEmail(String email) {
			this.email = email;
		}
		
		public String toString() {
			return StringUtil.toString(this, false, true);
		}
	}
	
	public static class XRXSDept{
		private String adminId;			//部门负责人ID
		private String city;   			//城市
		private String code;   			//部门编码
		private String departmentId;   	//部门ID
		private String name;   	        //部门名称
		private String parentId;   	    //上级部门ID
		private String remark;   	    //备注
		private Integer type;           //类型
		
		public String getAdminId() {
			return adminId;
		}
		public void setAdminId(String adminId) {
			this.adminId = adminId;
		}
		public String getCity() {
			return city;
		}
		public void setCity(String city) {
			this.city = city;
		}
		public String getCode() {
			return code;
		}
		public void setCode(String code) {
			this.code = code;
		}
		public String getDepartmentId() {
			return departmentId;
		}
		public void setDepartmentId(String departmentId) {
			this.departmentId = departmentId;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			name = name.replaceAll("[x00-xff]", "").replace("\u00a0", "");;
//			name = name.replaceAll("[^\u4e00-\u9fa5\\-a-zA-Z0-9]", "");
			this.name = name;
		}
		public String getParentId() {
			return parentId;
		}
		public void setParentId(String parentId) {
			this.parentId = parentId;
		}
		public String getRemark() {
			return remark;
		}
		public void setRemark(String remark) {
			this.remark = remark;
		}
		public Integer getType() {
			return type;
		}
		public void setType(Integer type) {
			this.type = type;
		}   	
		
		public String toString() {
			return StringUtil.toString(this, false, true);
		}
	}
}
